package com.bookstore.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookstore.back.common.Result;
import com.bookstore.back.entity.News;
import com.bookstore.back.entity.NewsCategory;
import com.bookstore.back.mapper.NewsCategoryMapper;
import com.bookstore.back.mapper.NewsCategoryRelationMapper;
import com.bookstore.back.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户端新闻控制器
 * 
 * @author 程序猿_Ti
 * @since 2025-07-23
 */
@Slf4j
@RestController
@RequestMapping("/news")
@CrossOrigin(origins = "*")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private NewsCategoryMapper newsCategoryMapper;

    @Autowired
    private NewsCategoryRelationMapper newsCategoryRelationMapper;

    /**
     * 获取公开的新闻列表（只返回已上线的新闻）
     */
    @GetMapping("/list")
    public Result<IPage<News>> getPublicNewsList(@RequestParam Map<String, Object> params) {
        try {
            // 分页参数
            int current = Integer.parseInt(params.getOrDefault("current", "1").toString());
            int size = Integer.parseInt(params.getOrDefault("size", "10").toString());
            
            // 查询条件
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            
            // 只查询已上线的新闻
            queryWrapper.eq("status", 1);
            
            // 标题搜索
            String title = (String) params.get("title");
            if (StringUtils.isNotBlank(title)) {
                queryWrapper.like("title", title);
            }
            
            // 作者搜索
            String author = (String) params.get("author");
            if (StringUtils.isNotBlank(author)) {
                queryWrapper.like("author", author);
            }
            
            // 分类筛选
            String categoryName = (String) params.get("category");
            if (StringUtils.isNotBlank(categoryName) && !"全部".equals(categoryName)) {
                // 根据分类名称查找分类ID
                QueryWrapper<NewsCategory> categoryQuery = new QueryWrapper<>();
                categoryQuery.eq("name", categoryName).eq("status", 1);
                NewsCategory category = newsCategoryMapper.selectOne(categoryQuery);

                if (category != null) {
                    // 根据分类ID查找新闻ID列表
                    List<Integer> newsIds = newsCategoryRelationMapper.getNewsIdsByCategoryId(category.getId());
                    if (!newsIds.isEmpty()) {
                        queryWrapper.in("id", newsIds);
                    } else {
                        // 如果该分类下没有新闻，返回空结果
                        queryWrapper.eq("id", -1);
                    }
                }
            }
            
            // 按发布时间倒序
            queryWrapper.orderByDesc("publish_time");
            
            IPage<News> newsPage = newsService.page(new Page<>(current, size), queryWrapper);
            return Result.success(newsPage);
        } catch (Exception e) {
            log.error("获取新闻列表失败：{}", e.getMessage());
            return Result.error("获取新闻列表失败");
        }
    }

    /**
     * 获取新闻详情
     */
    @GetMapping("/{newsId}")
    public Result<News> getNewsDetail(@PathVariable Integer newsId) {
        try {
            News news = newsService.getById(newsId);
            if (news == null || news.getStatus() != 1) {
                return Result.error("新闻不存在或已下线");
            }
            
            // 增加浏览量
            news.setViewCount(news.getViewCount() + 1);
            newsService.updateById(news);
            
            return Result.success(news);
        } catch (Exception e) {
            log.error("获取新闻详情失败：{}", e.getMessage());
            return Result.error("获取新闻详情失败");
        }
    }

    /**
     * 获取推荐新闻列表
     */
    @GetMapping("/recommended")
    public Result<List<News>> getRecommendedNews(@RequestParam(defaultValue = "5") Integer limit) {
        try {
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                       .eq("is_recommended", 1)
                       .orderByDesc("publish_time")
                       .last("LIMIT " + limit);
            
            List<News> recommendedNews = newsService.list(queryWrapper);
            return Result.success(recommendedNews);
        } catch (Exception e) {
            log.error("获取推荐新闻失败：{}", e.getMessage());
            return Result.error("获取推荐新闻失败");
        }
    }

    /**
     * 获取热门新闻列表（按浏览量排序）
     */
    @GetMapping("/popular")
    public Result<List<News>> getPopularNews(@RequestParam(defaultValue = "5") Integer limit) {
        try {
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                       .orderByDesc("view_count")
                       .orderByDesc("publish_time")
                       .last("LIMIT " + limit);
            
            List<News> popularNews = newsService.list(queryWrapper);
            return Result.success(popularNews);
        } catch (Exception e) {
            log.error("获取热门新闻失败：{}", e.getMessage());
            return Result.error("获取热门新闻失败");
        }
    }

    /**
     * 获取最新新闻列表
     */
    @GetMapping("/latest")
    public Result<List<News>> getLatestNews(@RequestParam(defaultValue = "5") Integer limit) {
        try {
            QueryWrapper<News> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1)
                       .orderByDesc("publish_time")
                       .last("LIMIT " + limit);

            List<News> latestNews = newsService.list(queryWrapper);
            return Result.success(latestNews);
        } catch (Exception e) {
            log.error("获取最新新闻失败：{}", e.getMessage());
            return Result.error("获取最新新闻失败");
        }
    }

    /**
     * 获取新闻分类列表
     */
    @GetMapping("/categories")
    public Result<List<NewsCategory>> getNewsCategories() {
        try {
            QueryWrapper<NewsCategory> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", 1).orderByAsc("sort_order");

            List<NewsCategory> categories = newsCategoryMapper.selectList(queryWrapper);
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取新闻分类失败：{}", e.getMessage());
            return Result.error("获取新闻分类失败");
        }
    }
}
